import 'dart:async';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wk_robot2/app/event/DataCallBack.dart';
import 'package:wk_robot2/app/event/MsgContentEvent.dart';
import 'package:wk_robot2/app/nets/NetWorkManager.dart';
import 'package:wk_robot2/app/utils/CommonUtil.dart';

import '../../../../generated/AlphaResponse.pb.dart';
import '../../../../generated/GetRobotConfiguration.pb.dart';
import '../../../logger/Logger.dart';
import '../../../models/ActionItem.dart';
import '../../../robot_comm/cmd_const.dart';
import '../../../robot_comm/event_handler.dart';
import '../../../robot_comm/mqtt_comm_manager.dart';

//这个类作废了, 全部在action_squares_view3里面实现.
@deprecated
class ActionSquaresController extends GetxController {
  var robotWhetherOnline = false.obs;
  Map<String,List<ActionItem>> actionMp = Map<String, List<ActionItem>>();

  var pageController = PageController().obs;
  var totalPages = 3.obs;
  var isScrolling = false.obs;
  var currentPage = 0.obs;

  var mNetSubscription =  null;

  var hasNetWork = false.obs;


  @override
  void onInit() {
    super.onInit();

    pageController.value.addListener(() {
      if (isScrolling.value) return; // 如果正在滚动，则忽略此次监听

      final double page = pageController.value.page!;

      if (page >= totalPages.value) {
        isScrolling.value = true;// 设置标志为正在滚动
        pageController.value.animateToPage(
           0,
          duration: Duration(milliseconds: 300),
          curve: Curves.ease,
        ).then((_) => isScrolling.value = false); // 动画完成后重置标志
      } else if (page < 0) {
        isScrolling.value = true;
        pageController.value.animateToPage(
          totalPages.value - 1,
          duration: Duration(milliseconds: 300),
          curve: Curves.ease,
        ).then((_) => isScrolling.value = false);
      }
    });

    robotWhetherOnline.value = CommonUtil.getCurrentSelectedRobot().isOnline!;

    getActionSquares();

    monitorNetWork();

  }

  void monitorNetWork() async {
    final List<ConnectivityResult> connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult.contains(ConnectivityResult.mobile) || connectivityResult.contains(ConnectivityResult.wifi)) {
      hasNetWork.value = true;
    } else {
      hasNetWork.value = false;
    }


    mNetSubscription = Connectivity().onConnectivityChanged.listen((List<ConnectivityResult> result) {
      // Received changes in available connectivity types!
      if (result.contains(ConnectivityResult.mobile) || result.contains(ConnectivityResult.wifi)) {
        hasNetWork.value = true;
      } else {
        hasNetWork.value = false;
      }

    });
  }

  @override
  void onReady() {
    super.onReady();
    eventBus.on<ProductContentEvent>().listen((event) {
         if(event.code == ROBOT_LIST_HAVE_CHANGED) {
           robotWhetherOnline.value = CommonUtil.getCurrentSelectedRobot().isOnline;

         }
    });


    
  }


  @override
  void onClose() {
    super.onClose();
    pageController.value.dispose();
    if (mNetSubscription != null) {
      mNetSubscription.cancel();
    }
  }


  void getActionSquares() {
       //分为在线或不在线.
       if (!robotWhetherOnline.value) {
         loadingData('Alpha_Mini-UBT','');
       } else {
         GetRobotConfigurationRequest request = GetRobotConfigurationRequest();
         MqttCommManager().sendCmd(CmdConst.IM_GET_ROBOT_CONFIG_REQUEST, request, (AlphaResponse msg){
           GetRobotConfigurationResponse response = GetRobotConfigurationResponse.fromBuffer(msg.bodyData);
           loadingData('Alpha_Mini-UBT',response.hardwareversion);

         });
       }




  }


  void loadingData(String channel,String version) {
    NetWorkManager.getInstance().requestBussiness(NetWorkManager.ACTIONSQUARE_ALL, {
      'channel': channel,
      'version': version,
    }, NetWorkManager.methodGET, DataCallBack(
        businessCallBack: (data) {
          data.forEach((item) {
            ActionItem actionItem = ActionItem.fromJson(item);
            List<ActionItem> actionItems = actionMp[actionItem.actionType] ?? [];
            actionItems.add(actionItem);
            actionMp[actionItem.actionType!] = actionItems;
          });
        }
    ));
  }

  void setCurrentPage(int index) {
     currentPage.value = index;
  }

  int getCurrentPage() {
    return currentPage.value;
  }

  int getTotalPage() {
    return totalPages.value;
  }
}


